/*==========================
demo.js  http://plugins.jquery.com/soap/ or https://github.com/doedje/jquery.soap
part of the jQuery.soap distribution version: 1.4.4

this file contains the javascript for the jQuery.soap demo
===========================*/

$(document).ready(function() {
	$('#test').click(function(e) {
		// stop the form to be submitted...
		e.preventDefault();
		// empty all elements with results and feedback
		$('#feedbackHeader, #feedback, #soapcall, #requestXML').empty();
		// gather the data
		var data = $('#data').val();
		if ($('#dataType').val() == 'json') {
			data = eval("("+data+")");
		}else{
			var xml = '<xml>'+data+'</xml>';
		 
			data = $.xml2json(xml); 
		}

		var namespaceURL=$('#namespaceURL').val();
		if(namespaceURL.indexOf("http://")== -1){
	
			namespaceURL="http://"+namespaceURL.split(".").reverse().join(".");
		}
		

		$.soap({
			url: $('#url').val(),
			method: $('#method').val(),

			appendMethodToURL:true,
			async:true,

			data: data,
			envAttributes: {
				/*'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
				'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema'*/
			},

			namespaceQualifier: 'ns1',
			namespaceURL: namespaceURL,
			
			elementName: $('#elementName').val(),
			noPrefix: true,
			enableLogging: true,

			beforeSend: function(SOAPEnvelope) {
				var str =SOAPEnvelope.toString();
			
				 
				  
				  $('#requestXML').text(print(str));

			},
			success: function(SOAPResponse) {
				$('#feedbackHeader').html('Response: Success!');
				//$('#feedback').text(SOAPResponse.toXML());
				$('#feedback').text(SOAPResponse);
				   // scroll to the bottom
				$("#feedback").scrollTop(1000000);

			},
			error: function(SOAPResponse) {
				$('#feedbackHeader').html('Response: Error!');
			//	$('#feedback').text(SOAPResponse.toString());
			}
		});
	});
});
function print(str,tabcount) {
	  str =str.replace(new RegExp('\r</','gm'),'</');
	  str =str.replace(new RegExp('><','gm'),'>\r<');
	
	  var xmlout =str.split(new RegExp('\r|\n','gm'));
	  var tabs = '  ';
	  tabcount = (tabcount) ? tabcount : 0;
	  var xmldom =[];
	  for (var j = 2; j < xmlout.length-1; j++) {
		 if(xmlout[j].startWith('</')){
			  xmlout[j]=repeat(tabs, --tabcount)+xmlout[j];
		  } else if(xmlout[j-1].testWith('</|/>')){
			  xmlout[j]=repeat(tabs,tabcount)+xmlout[j];
			
		  }else if (xmlout[j].startWith('<')){
			  xmlout[j]=repeat(tabs,++tabcount)+xmlout[j];
			
		  }
		  
		  
	  }
	  
	  

	return   xmlout.join('\r');
	
}


String.prototype.startWith=function(str){     
  var reg=new RegExp("^"+str);     
  return reg.test(this);        
}  
String.prototype.endWith=function(str){     
	  var reg=new RegExp(str+"$");     
	  return reg.test(this);        
	}
String.prototype.testWith=function(str){     
	  var reg=new RegExp(str);     
	  return reg.test(this);        
	}


function repeat(x, n) {
	var s = '';
	for (;;) {
		if (n & 1) s += x;
		n >>= 1;
		if (n) x += x;
		else break;
	}
	return s;
}
